import React, { useEffect, useState, useRef } from 'react';
import { Dropdown, Space } from 'antd';
import { FixedSizeList as List } from 'react-window';
import '../../style/playerLists.css';
import '../../style/kuangjia.css';
import { useGlobalContext } from '../GlobalContext';

const PlayerLists = () => {
  const { playerlistfresh, setPlayerlistRefresh,
    currentIndex, setCurrentIndex
  } = useGlobalContext();
  const [songData, setSongData] = useState([]);
  const [isFetched, setIsFetched] = useState(false);
  const listRef = useRef(null);

  // 获取歌曲播放地址
  const getPlayUrl = async (id) => {
    try {
      const response = await fetch(`http://localhost:3000/song/url?id=${id}`);
      const data = await response.json();
      return data.data[0]?.url || '';
    } catch (error) {
      console.error('Error fetching song URL:', error);
      return '';
    }
  };

  // 获取播放列表数据
  const fetchSongData = async () => {
    if (isFetched) return;
    try {
      const response = await fetch('http://localhost:8088/playing/allsortBysongIndex');
      const data = await response.json();

      const songs = await Promise.all(
        data.data.map(async (song) => ({
          ...song,
          playUrl: await getPlayUrl(song.musicId),
          lyricUrl: `http://localhost:3000/lyric?id=${song.musicId}`,
          artName: song.artName || '未知',
        }))
      );

      setSongData(songs);
      setIsFetched(true);
    } catch (error) {
      console.error('Error fetching song data:', error);
    }
  };

  useEffect(() => {
    fetchSongData();
  }, [playerlistfresh]);

  // 清空播放列表
  const handleDeleteAll = async () => {
    try {
      const response = await fetch('http://localhost:8088/playing/deleteall', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
      });

      if (!response.ok) {
        throw new Error('Failed to delete all songs');
      }
      setPlayerlistRefresh(!playerlistfresh);
    } catch (error) {
      console.error('Error deleting all songs:', error);
    }
  };

  //歌曲选择播放
  const handleSongPlayClick = (index) => {
    setCurrentIndex(index)
  }

  //删除歌曲
  const handleDeletefromSonglist = async (songId) => {
    try {
      const response = await fetch(`http://localhost:8088/playing/${songId}`, {
        method: "DELETE",
      });

      if (!response.ok) {
        throw new Error("Failed to remove song from favorites");
      }
      setPlayerlistRefresh(!playerlistfresh);
      // setPerSonglistRefresh(!persongListrefresh);
    } catch (error) {
      console.error("Error handling favor request: ", error);
    }
  }

  // 右键菜单选项
  const items = (songId) => [
    {
      key: '1',
      label: (
        <a>
          收藏
        </a>
      ),
    },
    {
      key: '2',
      label: (
        <a onClick={() => handleDeletefromSonglist(songId)}>
          删除
        </a>
      ),
    },
    {
      key: '3',
      label: (
        <a>
          添加到歌单
        </a>
      ),
    },
    {
      key: '4',
      label: (
        <a>
          添加到播放
        </a>
      ),
    },
  ];

  // 渲染单行歌曲数据
  const renderRow = ({ index, style }) => {
    const song = songData[index];
    return (
      <li
        key={song.musicId}
        style={style}
        className={currentIndex === index ? "playing" : ""}
        onDoubleClick={() => handleSongPlayClick(index)}
      >
        {currentIndex === index ? (
          <div className='icon5'>
            <span className='playing1'></span>
          </div>) : (
          <div className="hideicon5">
            <i className="ri-play-fill"></i>
          </div>)}
        <div className="hideicon6">
          <i className="ri-heart-3-line"></i>
        </div>
        <div className="hideicon7">
          <Space>
            <Dropdown
              menu={{ items: items(song.musicId) }}
              placement="topLeft"
              trigger={['click']}
            >
              <i className="ri-menu-4-line"></i>
            </Dropdown>
          </Space>
        </div>
        <div className="playerlists_songImg">
          <img src={song.coverUrl} alt={song.musicName} />
        </div>
        <div className="song_name">
          <span id="songname">{song.musicName}</span>
          <span id="singer">{song.artName}</span>
        </div>
      </li>
    );
  };

  return (
    <div className="playerlists_con">
      <div className="playerlistsTitle">
        <p>播放队列</p>
        <span className="deleteall" onClick={handleDeleteAll}>
          删除所有
        </span>
      </div>
      <div className="playerLists_main" ref={listRef}>
        <List
          height={listRef.current ? listRef.current.clientHeight : 400} // 默认高度为 400
          itemCount={songData.length}
          itemSize={50}
          width="100%"
        >
          {renderRow}
        </List>
      </div>
    </div>
  );
};

export default PlayerLists;
